package org.example.camundaexternaltask.tasks;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.engine.variable.Variables;
import org.example.camundaexternaltask.configs.CamundaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description:
 */

@Slf4j
@Component("shoppingTask")
public class ShoppingTask {
    @Autowired
    private CamundaConfig camundaConfig;

    private ExternalTaskClient externalTaskClient = null;

    @PostConstruct
    public void init() {
        getExternalTaskClient();
        handleShoppingCart();
        handlePay();
        handleLogisticDeliver();
    }

    public ExternalTaskClient getExternalTaskClient() {
        if (externalTaskClient == null) {
            externalTaskClient = ExternalTaskClient.create()
                    .baseUrl(camundaConfig.getUrl())
                    .asyncResponseTimeout(camundaConfig.getTimeout())
                    .build();
        }
        return externalTaskClient;
    }

    /**
     * 订阅一个Service（external类型）
     */
    public void handleShoppingCart() {
        /**
         * 订阅服务
         * 订阅的是加入购物车服务
         * shopping_cart：加入购物车节点的 Topic
         */
        externalTaskClient.subscribe("shopping_cart")
                /**
                 * 流程定义，即所属流程 id
                 */
                .processDefinitionKey("Process_shopping")
                /**
                 * 最长加锁时间
                 */
                .lockDuration(2000)

                /**
                 * 订阅配置
                 * ===========
                 * 处理区域
                 *
                 * externalTask 外部传参相关
                 *
                 * externalTaskService 流程执行相关
                 */
                .handler((externalTask, externalTaskService) -> {
                    /**
                     * 处理逻辑
                     */
                    log.info("开始加入到购物车");
                    Map<String, Object> goodVariable = Variables.createVariables()
                            // 添加变量
                            .putValue("size", "xl")
                            .putValue("count", 2);
                    log.info("已加入到购物车：{}", goodVariable);
                    /**
                     * 执行完成
                     */
                    externalTaskService.complete(externalTask, goodVariable);
                }).open();
    }

    /**
     * 订阅 付款 服务
     */
    public void handlePay() {
        externalTaskClient.subscribe("pay")
                .processDefinitionKey("Process_shopping")
                .lockDuration(2000)
                .handler(((externalTask, externalTaskService) -> {
                    log.info("开始付款");
                    Object size = externalTask.getVariable("size");
                    Object count = externalTask.getVariable("count");
                    log.info("读取购物车中的参数，size: {}, count: {}", size, count);
                    Map<String, Object> payVariable = Variables.createVariables()
                            // 添加变量
                            .putValue("toWhere", "成都");
                    log.info("结束付款，填写目的地:{}", payVariable);
                    externalTaskService.complete(externalTask, payVariable);
                })).open();
    }

    /**
     * 订阅 物流发货 服务
     */
    public void handleLogisticDeliver() {
        externalTaskClient.subscribe("logistic_deliver")
                .processDefinitionKey("Process_shopping")
                .lockDuration(2000)
                .handler(((externalTask, externalTaskService) -> {
                    Object toWhere = externalTask.getVariable("toWhere");
                    log.info("即将发往目的地:{}", toWhere);
                    externalTaskService.complete(externalTask);
                })).open();
    }
}
